//
//  YCYTXIMDBManager.m
//  DemoYTX
//
//  Created by 唐可雄 on 16/7/12.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCYTXIMDBManager.h"

#import "FMDB.h"
#import <CommonCrypto/CommonDigest.h>

@interface YCYTXIMDBManager ()

/// 数据库
@property (strong, nonatomic) FMDatabase *database;

@end

@implementation YCYTXIMDBManager

#pragma mark - Life Cycle

+ (instancetype)instanceWithUserID:(NSString *)userID {
    YCYTXIMDBManager *manager = [[YCYTXIMDBManager alloc] init];
    
    [manager openDatabaseWithUserID:userID];
    
    return manager;
}

#pragma mark - Private Methods

#pragma mark - 数据库操作

- (void)openDatabaseWithUserID:(NSString *)userID {
    if (userID.length == 0) {
        return;
    }
    // Documents:
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    // userID md5 作为数据库所在的文件夹名
    const char *cStr = [userID UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    NSString* MD5 =  [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];
    // 数据库文件夹
    NSString * documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:MD5];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:documentsDirectory isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir) {
            NSLog(@"Create Database Directory Failed.");
        }
    }
    
    NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"im.db"];
    if (self.database) {
        [self.database close];
        self.database = nil;
    }
    
    self.database = [FMDatabase databaseWithPath:dbPath];
    [self.database open];
    
    [self createMemberTable];
    [self createIMGroupIDTable];
    [self createIMGroupNoticeTable];
    [self createSessionTable];
    [self createIMTrigger];
}

#pragma mark - 表操作

/// 判断指定表是否存在
- (BOOL)checkTableExist:(NSString *)tableName {
    BOOL result = NO;
    NSString* lowtableName = [tableName lowercaseString];
    
    FMResultSet *rs = [self.database executeQuery:@"SELECT [sql] FROM sqlite_master WHERE [type] = 'table' AND lower(name) = ?", lowtableName];
    result = [rs next];
    [rs close];
    
    return result;
}

/// 创建表
- (void)createTable:(NSString*)tableName sql:(NSString *)createSql {
    BOOL isExist = [self.database tableExists:tableName];
    if (!isExist) {
        [self.database executeUpdate:createSql];
    }
}

/// 创建成员表
- (void)createMemberTable{
    [self createTable:@"userName" sql:@"CREATE table userName (userid TEXT NOT NULL PRIMARY KEY UNIQUE ON CONFLICT REPLACE, nickName TEXT, sex INTEGER)"];
}

/// 创建群组id表
- (void)createIMGroupIDTable {
    [self createTable:@"im_groupinfo2" sql:@"CREATE table im_groupinfo2 (groupId TEXT NOT NULL PRIMARY KEY UNIQUE ON CONFLICT REPLACE, type INTEGER, groupname TEXT, isNotice bool); create unique index groupinfo_info_index2 on im_groupinfo2(groupId)"];
    BOOL isExist = [self.database tableExists:@"im_groupinfo"];
    if (isExist) {
        [self.database executeUpdate:@"INSERT INTO im_groupinfo2 SELECT *,YES FROM im_groupinfo"];
        [self.database executeUpdate:@"DROP TABLE IF EXISTS im_groupinfo"];
        [self.database executeUpdate:@"DROP INDEX IF EXISTS groupinfo_info_index"];
    }
}

/// 创建群组通知表
- (void)createIMGroupNoticeTable {
    [self createTable:@"im_groupnotice" sql:@"CREATE table im_groupnotice(ID INTEGER PRIMARY KEY AUTOINCREMENT,groupId varchar(32),groupName varchar(32),type INTEGER,admin varchar(32),member varchar(32),nickName varchar(32), declared varchar(32), dateCreated INTEGER, isRead INTEGER, confirm INTEGER, sender varchar(32))"];
    if (![self.database columnExists:@"isDiscuss" inTableWithName:@"im_groupnotice"]) {
        [self.database executeUpdate:@"alter table im_groupnotice add isDiscuss integer default 0"];
    }
}

/// 创建会话表
- (void)createSessionTable {
    [self createTable:@"session" sql:@"CREATE table session (sessionId TEXT NOT NULL PRIMARY KEY UNIQUE ON CONFLICT REPLACE, dateTime INTEGER,type INTEGER,text varchar(2048),unreadCount INTEGER,sumCount INTEGER,state INTEGER)"];
    if (![self.database columnExists:@"isAt" inTableWithName:@"session"]) {
        [self.database executeUpdate:@"alter table session add isAt integer default 0"];
    }
}

/// 创建触发器
- (void)createIMTrigger {
    BOOL result = NO;
    FMResultSet *rs = [self.database executeQuery:@"SELECT [sql] FROM sqlite_master WHERE [type] = 'trigger' AND lower(name) = ?", @"delete_obsolete_im"];
    result = [rs next];
    [rs close];
    if (result) {
        [self.database executeUpdate:@"DROP TRIGGER delete_obsolete_im"];
        [self.database executeUpdate:@"DROP TRIGGER im_update_thread_on_insert"];
        [self.database executeUpdate:@"DROP TRIGGER im_update_thread_on_update"];
    }
}

@end
